package com.hyyt.shopjsp.settlement.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.returnsApply.pojo.ShopReturnsApply;
import com.hyyt.shopjsp.returnsApply.service.IShopReturnsApplyService;
import com.hyyt.shopjsp.settlement.pojo.ShopSettlementDetail;
import com.hyyt.shopjsp.settlement.service.IShopSettlementDetailService;
import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SHOP_店铺申请结算明细 Controller
 * LC
 */
@Controller
@RequestMapping("/back/shopSettlement")
public class ShopSettlementDetailController  extends BaseController {

    private Logger log = Logger.getLogger(ShopSettlementDetailController.class);
    private String basePath = "/back/shop/settlement/";

    @Resource
    private IShopSettlementDetailService shopSettlementDetailService;//店铺结算明细service接口
    @Resource
    private IShopReturnsApplyService shopReturnsApplyService;//店铺退货service接口

    /**
     * 进入店铺申请结算明细页
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoShopSettlementDetailPage")
    public String gotoShopSettlementDetailPage(){
        return basePath+"shopSettlementListDetailList";
    }

    /**
     * 店铺申请结算明细列表
     * @param response
     * @param shopName          店铺名称
     * @param status            状态：1.待审核 2.审核通过 3.审核未通过 4.已结算
     * @param createDateStart   申请开始日期
     * @param createDateEnd     申请结束日期
     */
    @RequestMapping(value="listShopSettlementDetail",method= RequestMethod.POST)
    @ResponseBody
    public void listShopSettlementDetail(String shopName,String status,String createDateStart,String createDateEnd,Page page, HttpServletResponse response){
        Map<String, Object> param = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            param.put("shopName",shopName.trim());
        }
        if(Utils.objectIsNotEmpty(status)){
            param.put("status",status);
        }
        if(Utils.objectIsNotEmpty(createDateStart)){
            param.put("createDateStart",createDateStart);
        }
        if(Utils.objectIsNotEmpty(createDateEnd)){
            param.put("createDateEnd",createDateEnd);
        }
        param.put("sortColumns", "settlementId desc");
        int totalRecordCount =shopSettlementDetailService.countShopSettlementDetail(param);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<ShopSettlementDetail> shopSettlementDetailList =shopSettlementDetailService.queryShopSettlementDetail(param, page.getPageRecordBeginIndex(), page.getPageSize());
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", shopSettlementDetailList);// rows键 存放每页记录 list
        ResultMsg.create(param, response);  //把内容发送到页面
    }

    /**
     * 根据店铺申请结算明细id获得对象
     *
     * @param settlementId  店铺申请结算明细Id
     *
     */
    @RequestMapping(value = "getShopSettlementDetailObject", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getShopSettlementDetailObject(Integer settlementId) {
        if (Utils.objectIsNotEmpty(settlementId)) {
            ShopSettlementDetail shopSettlementDetail = shopSettlementDetailService.loadShopSettlementDetail(settlementId);
            return ResultMsg.create(true, null, FastJsonUtils.toJSONString(shopSettlementDetail));
        }
        return ResultMsg.create(false);
    }

    /**
     * 修改店铺申请结算明细状态
     *
     * @param settlementId  店铺申请结算明细Id
     * @param status        状态：1.待审核 2.审核通过 3.审核未通过 4.已结算
     * @return
     */
    @RequestMapping(value = "updateShopSettlementDetailStatus", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg updateShopSettlementDetailStatus(String settlementId,String status) {
        Map<String ,Object> params = new HashMap<>();
        if (Utils.objectIsNotEmpty(settlementId) && Utils.objectIsNotEmpty(status)) {
            params.put("settlementId",settlementId);
            params.put("status",status);
            shopSettlementDetailService.updateShopSettlementDetailStatus(params);
            return ResultMsg.create(true);
        }
        return ResultMsg.create(false);
    }

    /**
     * 修改店铺申请结算明细支付信息
     *
     * @param settlementId  店铺申请结算明细Id
     * @param paymentInfo   平台给店铺结算后的支付信息
     * @return
     */
    @RequestMapping(value = "updateShopSettlementDetailPaymentInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg updateShopSettlementDetailPaymentInfo(String settlementId,String paymentInfo) {
        Map<String ,Object> params = new HashMap<>();
        if (Utils.objectIsNotEmpty(settlementId) && Utils.objectIsNotEmpty(paymentInfo)) {
            params.put("settlementId",settlementId);
            params.put("paymentInfo",paymentInfo);
            params.put("status","4");
            shopSettlementDetailService.updateShopSettlementDetailPaymentInfo(params);
            return ResultMsg.create(true);
        }
        return ResultMsg.create(false);
    }

    /**
     * 根据店铺结算ID查询未结算订单列表
     * @param response
     * @param settlementId        店铺申请结算明细Id
     * @param ordersNo            订单号
     */
    @RequestMapping(value="listSettlementOrdersBySettlementId",method= RequestMethod.POST)
    @ResponseBody
    public void listSettlementOrdersBySettlementId(String settlementId,String ordersNo,Page page, HttpServletResponse response){
        ShopSettlementDetail shopSettlementDetail = shopSettlementDetailService.loadShopSettlementDetail(Integer.parseInt(settlementId));
        Map<String, Object> param = new HashMap<>();
        if(Utils.objectIsNotEmpty(ordersNo)){
            param.put("ordersNo",ordersNo.trim());
        }
        if(Utils.objectIsNotEmpty(shopSettlementDetail.getOrdersIds())){
            param.put("ordersIds",shopSettlementDetail.getOrdersIds().split(","));
        }
        BigDecimal commissionProportion = shopSettlementDetail.getCommissionProportion();
        int totalRecordCount =shopSettlementDetailService.countSettlementOrdersBySettlementId(param);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<Map<String,Object>> settlementOrdersList =shopSettlementDetailService.querySettlementOrdersBySettlementId(param, page.getPageRecordBeginIndex(), page.getPageSize());
        for(Map<String,Object> map:settlementOrdersList){
            BigDecimal rakeAmount = new BigDecimal(0);//平台抽取营业额让利金额
            BigDecimal finalAmount = new BigDecimal(0);//订单消费金额
            BigDecimal changeAmount = new BigDecimal(0);//积分抵扣金额
            if(Utils.objectIsNotEmpty(map.get("finalAmount"))){
                finalAmount = new BigDecimal(String.valueOf(map.get("finalAmount")));
            }
            if(Utils.objectIsNotEmpty(map.get("changeAmount"))){
                changeAmount = new BigDecimal(String.valueOf(map.get("changeAmount")));
            }
            //平台抽取营业额让利金额rakeAmount
            if(Utils.objectIsNotEmpty(commissionProportion)){
                rakeAmount = finalAmount.add(changeAmount).multiply(commissionProportion).multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            map.put("rakeAmount",rakeAmount);
            BigDecimal returnAmountTotal = new BigDecimal(0);//退货返还总金额
            BigDecimal changeAmountTotal = new BigDecimal(0);//退货返还财富券总金额
           if(Utils.objectIsNotEmpty(map.get("isReturn"))){
                if(Utils.objectIsNotEmpty(map.get("ordersId"))){
                    param.clear();
                    param.put("ordersId",map.get("ordersId").toString());
                    List<ShopReturnsApply> shopReturnsApplyList = shopReturnsApplyService.queryShopReturnsApply(param);
                    if(Utils.objectIsNotEmpty(shopReturnsApplyList)){
                        for(ShopReturnsApply shopReturnsApply:shopReturnsApplyList){
                            //有申请退货且退货已完成
                            if(Utils.objectIsNotEmpty(shopReturnsApply)&&Utils.objectIsNotEmpty(shopReturnsApply.getApplyState())&&Utils.objectIsNotEmpty(shopReturnsApply.getReturnsState())){
                                //审核状态：1 等待处理 2 同意 3 拒绝
                                if(shopReturnsApply.getApplyState()==2&&shopReturnsApply.getReturnsState()>=4){
                                    returnAmountTotal = returnAmountTotal.add(shopReturnsApply.getReturnAmount());
                                    changeAmountTotal = changeAmountTotal.add(shopReturnsApply.getChangeAmount().multiply(new BigDecimal(shopReturnsApply.getCount())));
                                }
                            }
                        }
                    }
                }
           }
            map.put("changeAmountTotal",changeAmountTotal);
            map.put("returnAmountTotal",returnAmountTotal);
        }
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", settlementOrdersList);// rows键 存放每页记录 list
        ResultMsg.create(param, response);  //把内容发送到页面
    }

    /**
     * 导出平台与店铺结算excel
     * @param shopName
     * @param status
     * @param createDateStart
     * @param createDateEnd
     * @param request
     * @param response
     */
    @RequestMapping("exportShopSettlementDetailExcel")
    public void exportShopSettlementDetailExcel(String shopName, String status, String createDateStart, String createDateEnd, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        Map<String, Object> param = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            //用于get请求强转，防止中文乱码
            shopName= new String(shopName.trim().getBytes("iso8859-1"),"UTF-8");
            param.put("shopName",shopName);
        }
        if(Utils.objectIsNotEmpty(status)){
            param.put("status",status);
        }
        if(Utils.objectIsNotEmpty(createDateStart)){
            param.put("createDateStart",createDateStart);
        }
        if(Utils.objectIsNotEmpty(createDateEnd)){
            param.put("createDateEnd",createDateEnd);
        }
        param.put("sortColumns", "settlementId desc");
        List<ShopSettlementDetail> shopSettlementDetailList =shopSettlementDetailService.queryShopSettlementDetail(param);
        SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
        List<Map<String,Object>> shopSettlementDetail = new ArrayList<>();
        if(shopSettlementDetailList!=null&&shopSettlementDetailList.size()>0){
            for (ShopSettlementDetail shopSettlementDetail1 : shopSettlementDetailList) {
                Map<String,Object> map = new HashMap<>();
                map.put("companyName", shopSettlementDetail1.getCompanyName());
                map.put("shopName", shopSettlementDetail1.getShopName());
                map.put("totalCost", shopSettlementDetail1.getTotalCost());
                if(Utils.objectIsNotEmpty(shopSettlementDetail1.getRakeCost())){
                    map.put("rakeCost", shopSettlementDetail1.getRakeCost());
                }else{
                    map.put("rakeCost", "0.00");
                }
                map.put("commissionProportion", shopSettlementDetail1.getCommissionProportion());
                map.put("finaltTotalCost", shopSettlementDetail1.getFinaltTotalCost());
                map.put("rebateAmount", shopSettlementDetail1.getRebateAmount());
                switch (shopSettlementDetail1.getStatus()){
                    case 1:
                        map.put("status","待审核");
                        break;
                    case 2:
                        map.put("status","审核通过");
                        break;
                    case 3:
                        map.put("status","审核未通过");
                        break;
                    case 4:
                        map.put("status","已结算");
                        break;
                }
                map.put("createDate", formatter.format(shopSettlementDetail1.getCreateDate()));
                shopSettlementDetail.add(map);
            }
        }
        String fileName ="平台与店铺结算信息";
        String columnNames[] = {"公司名称","店铺名称","申请结算总额(元)","平台抽佣总额(元)","平台抽佣比例","实际结算总额(元)","抽佣返利金额(元)","结算状态","申请日期"};
        String keys[] = {"companyName","shopName","totalCost","rakeCost","commissionProportion","finaltTotalCost","rebateAmount","status","createDate"};
        try {
            ExportExcel.download(fileName,shopSettlementDetail,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }
    }
}
